from flask import Blueprint, request, jsonify
import os
import sys
import time
import configparser
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from public_listen_db import SQLServerDatabase, connection_string
from datetime import datetime


# 创建蓝图
public_listen_page = Blueprint('public_listen_page', __name__)


class MyHandler(FileSystemEventHandler):
    def __init__(self, db_instance, batch_insert_interval=1, batch_insert_size=1):
        self.db_instance = db_instance
        self.batch_insert_interval = batch_insert_interval
        self.batch_insert_size = batch_insert_size
        self.batch_insert_buffer = []
        self.last_insert_time = time.time()

    def on_created(self, event):
        if event.is_directory:
            return

        file_path = event.src_path

        if file_path.lower().endswith('.bin'):
            # print(f'New .bin file path: {repr(file_path)}, {datetime.now()}')

            # Use Unicode string for file path
            self.batch_insert_buffer.append((file_path,))

            self.check_and_execute_batch_insert()

    def on_moved(self, event):
        if event.is_directory:
            return

        old_file_path = os.path.abspath(event.src_path)
        new_file_path = os.path.abspath(event.dest_path)

        old_file_path = str(old_file_path)
        new_file_path = str(new_file_path)

        if old_file_path.lower().endswith('.bin') or new_file_path.lower().endswith('.bin'):
            # print(f'Renamed file path: {repr(new_file_path)},  {datetime.now()}')

            # Use Unicode strings for file paths
            self.batch_insert_buffer = [item for item in self.batch_insert_buffer if item[0] != old_file_path]
            self.batch_insert_buffer.append((new_file_path,))

            self.check_and_execute_batch_insert()

    def check_and_execute_batch_insert(self):
        current_time = time.time()

        if (current_time - self.last_insert_time >= self.batch_insert_interval) or \
                (len(self.batch_insert_buffer) >= self.batch_insert_size):
            with self.db_instance as db:
                db.execute_insert_many('test', self.batch_insert_buffer, ['binpath'])
            self.last_insert_time = current_time
            self.batch_insert_buffer = []

def watch_folder(folder_path):
    event_handler = MyHandler(db_instance)
    observer = Observer()
    observer.schedule(event_handler, path=folder_path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(0.5)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

config = configparser.ConfigParser()
os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
config.read('configs.ini', encoding='utf-8-sig')


folder_path = config['publicpath']['path1']
dbip = config['database']['server']
print(f'正在监听：【{folder_path}】 文件夹，数据库ip：{dbip}  启动时间：{datetime.now()}')
db_instance = SQLServerDatabase(connection_string)
watch_folder(folder_path)

if db_instance.batch_insert_buffer:
    with db_instance as db:
        db.execute_insert_many('test', db_instance.batch_insert_buffer, ['binpath'])
